/*-
 * Copyright (c) 2009 Jonathan Anderson
 * All rights reserved.
 *
 * WARNING: THIS IS EXPERIMENTAL SECURITY SOFTWARE THAT MUST NOT BE RELIED
 * ON IN PRODUCTION SYSTEMS.  IT WILL BREAK YOUR SOFTWARE IN NEW AND
 * UNEXPECTED WAYS.
 * 
 * This software was developed at the University of Cambridge Computer
 * Laboratory with support from a grant from Google, Inc. 
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/capability.h>
#include <sys/types.h>
#include <sys/procdesc.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <sys/wait.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>

#include <libcapability.h>
#include <libuserangel.h>

#include <iostream>

#include "TextEditor.h"

#include <QApplication>
#include <QFile>
#include <QMessageBox>

#include <X11/Xlib.h>
#include <X11/Xauth.h>
#include <xcb/xcb.h>

using namespace std;


extern "C" int _xcb_get_auth_info(int fd, xcb_auth_info_t *info, int display);


struct lc_library find_library(const char *name)
{
	struct lc_library lib;
	lib.lcl_libname = name;
	lib.lcl_fd = -1;

	char path[strlen(name) + 32];
	cap_rights_t rights = CAP_MASK_VALID ^ CAP_ACCEPT;

	const char *libdirs[] =
	{
		"/lib",
		"/usr/lib",
		"/usr/local/lib",
		"/usr/local/lib/qt4",
		NULL
	};

	for(int i = 0; libdirs[i]; i++)
	{
		sprintf(path, "%s/%s", libdirs[i], name);
//		lib.lcl_fd = ua_ropen(path, O_RDONLY, rights);
		// TODO: this is a kludge because mmap() fails in the child proc
		lib.lcl_fd = open(path, O_RDONLY);
		if(lib.lcl_fd >= 0) return lib;

		if(errno != ENOENT)
			err(EX_NOINPUT, "Error opening library %s", path);
	}

	err(-1, "Error opening %s with rights 0x%016llx\n", name, rights);
}


int connect_to_X(int*, xcb_auth_info_t*);



int main(int argc, char *argv[])
{
	cout << "host:\t\tIn sandbox: " << ld_insandbox() << endl;

	QApplication app(argc, argv);

	int my_fd = open(argv[0], O_RDONLY);
	char *sargv[2] = { (char*) "textcap", NULL };
	struct lc_sandbox *sandbox;
	struct lc_library libs[] =
	{
		// QtCore libraries
		find_library("libQtCore.so.4"),
		find_library("libuserangel.so.0"),
		find_library("libcapability.so.0"),
		find_library("libelf.so.1"),
		find_library("libz.so.5"),
		find_library("libgthread-2.0.so.0"),
		find_library("libglib-2.0.so.0"),
		find_library("libiconv.so.3"),
		find_library("libstdc++.so.6"),
		find_library("libm.so.5"),
		find_library("libgcc_s.so.1"),
		find_library("libthr.so.3"),
		find_library("libintl.so.8"),
		find_library("libpcre.so.0"),

		//QtGui Libraries
		find_library("libQtGui.so.4"),
		find_library("libpng.so.5"),
		find_library("libSM.so.6"),
		find_library("libICE.so.6"),
		find_library("libXi.so.6"),
		find_library("libXrender.so.1"),
		find_library("libXrandr.so.2"),
		find_library("libfreetype.so.9"),
		find_library("libfontconfig.so.1"),
		find_library("libXext.so.6"),
		find_library("libX11.so.6"),
		find_library("libxcb.so.2"),
		find_library("libXau.so.6"),
		find_library("libXdmcp.so.6"),
		find_library("librpcsvc.so.4"),
		find_library("libexpat.so.6"),

		//fontconfig
		find_library("libxml2.so.5"),
		find_library("libfreetype.so.9"),

		{ NULL, NULL, -1 }
	};

	int libcount = 0;
	while(libs[libcount].lcl_fd >= 0) libcount++;


	int ret = lch_startfd_libs(my_fd, "textcap", sargv,
	                           LCH_PERMIT_STDOUT | LCH_PERMIT_STDERR,
	                           libs, libcount, &sandbox);
	if(ret) err(EX_SOFTWARE, "Error starting sandbox");


	ua_set_client_name("Sandboxed Text Editor");
	int32_t angel = ua_find();
	if(angel < 0) err(EX_SOFTWARE, "Couldn't find user angel");
	else cout << "host:\t\tUser angel at FD " << angel << endl;

	int sandsock = -1;
	if(lch_getsock(sandbox, &sandsock)) err(EX_SOFTWARE, "Couldn't getsock");

	struct ua_datum *agent_datum = ua_marshall_string("user-angel", 10);
	if(ua_send(sandsock, agent_datum, &angel, 1) < 0)
	{
		cerr << "Error sending user angel FD: " << errno << " ("
		     << strerror(errno) << ")" << endl;
		return -1;
	}

	cout << "host:\t\tSent user angel FD (" << angel << ") to sandbox" << endl;

	int Xfd;
	xcb_auth_info_t xauth;

	if(connect_to_X(&Xfd, &xauth))
		err(EX_SOFTWARE, "Error connecting to X server");

	cout << "host:\t\tConnected to X at FD " << Xfd << endl;
	cout
		<< "host:\t\tauth info: " << endl
		<< "     \t\t\tname: ";

	for(int i = 0; i < xauth.namelen; i++) cout << xauth.name[i];
	cout
		<< endl
		<< "     \t\t\tdata: ";

	for(int i = 0; i < xauth.datalen; i++)
		printf("%02x ", xauth.data[i] & 0xff);
	cout << endl;


	struct ua_datum *d = ua_marshall_string("DISPLAY", 10);
	if(ua_send(sandsock, d, &Xfd, 1) < 0)
	{
		cerr << "Error sending X FD: " << errno << " ("
		     << strerror(errno) << ")" << endl;
		return -1;
	}
	cout << "host:\t\tSent X FD (" << angel << ") to sandbox" << endl;

	d = ua_marshall_string(xauth.name, xauth.namelen);
	if(ua_send(sandsock, d, NULL, 0) < 0)
	{
		cerr << "Error sending Xauth name: " << errno << " ("
		     << strerror(errno) << ")" << endl;
		return -1;
	}
	cout << "host:\t\tSent Xauth name to sandbox" << endl;

	d = ua_marshall_string(xauth.data, xauth.datalen);
	if(ua_send(sandsock, d, NULL, 0) < 0)
	{
		cerr << "Error sending Xauth data: " << errno << " ("
		     << strerror(errno) << ")" << endl;
		return -1;
	}
	cout << "host:\t\tSent Xauth data to sandbox" << endl;

	printf("======================================\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("======================================\n");
	fflush(stdout);


	int childproc = 0;
	if(lch_getprocdesc(sandbox, &childproc))
		err(EX_SOFTWARE, "Error getting sandbox process descriptor");

	struct pollfd fds[] = {
		{ childproc, POLLHUP | POLLERR, 0}, 
	};

	int count = poll(fds, 1, -1);
	if(count < 0) err(EX_SOFTWARE, "Error polling sandbox descriptor");


	return 0;
}


extern "C" int cap_main(int argc, char *argv[])
{
	printf("sandbox:\tIn sandbox: %i\n", ld_insandbox());
	fflush(stdout);

	printf("sandbox:\tOpening /etc/passwd directly... ");
	fflush(stdout);

	int tmp = open("/etc/passwd", O_RDONLY);
	if((tmp != -1) || (errno != ENOSYS))
		err(-1, "Was able to open /etc/passwd directly from sandbox");
	else
		printf("ENOSYS (sandbox working!)\n");
	fflush(stdout);



	// get a file descriptor for our host
	struct lc_host *lchpp;
	if(lcs_get(&lchpp) < 0) err(EX_IOERR, "Error getting lc_host");

	int host;
	if(lcs_getsock(lchpp, &host) < 0) err(EX_IOERR, "Error in lcs_getsock()");
	printf("sandbox:\tHost at FD %i\n", host);
	fflush(stdout);



	// find the User Angel
	int32_t angel = -1;
	uint32_t angellen = 1;
	struct ua_datum *d = ua_recv(host, &angel, &angellen);

	if(!d)
	{
		fprintf(stderr, "Received NULL datum\n");
		return -1;
	}

	if(angellen != 1)
	{
		fprintf(stderr, "Received %i FDs, not 1\n", angellen);
		return -1;
	}

	ua_set_client_name("Sandboxed Text Editor");
	ua_set(angel);



	// receive X file descriptor, Xauth data
	int32_t Xfd = -1;
	uint32_t Xfdlen = 1;
	d = ua_recv(host, &Xfd, &Xfdlen);

	if(!d)
	{
		fprintf(stderr, "Received NULL datum\n");
		return -1;
	}

	if(Xfdlen != 1)
	{
		fprintf(stderr, "Received %i FDs, not 1\n", Xfdlen);
		return -1;
	}

	printf("sandbox:\tX at FD %i\n", Xfd);
	fflush(stdout);

	char display[20];
	sprintf(display, "fd://cap:%i", Xfd);
	setenv("DISPLAY", display, 1);
	printf("sandbox:\tset DISPLAY to %s\n", getenv("DISPLAY"));
	fflush(stdout);


	d = ua_recv(host, NULL, 0);
	if(!d)
	{
		fprintf(stderr, "Received NULL datum\n");
		return -1;
	}

	unsigned int xauthnamelen = 50;
	char xauthname[xauthnamelen];
	if(ua_unmarshall_string(d, xauthname, &xauthnamelen) < 0)
		err(EX_IOERR, "Error unmarshalling Xauth name");

	printf("sandbox:\tXauth name: %s\n", xauthname);
	fflush(stdout);

	d = ua_recv(host, NULL, 0);
	if(!d)
	{
		fprintf(stderr, "Received NULL datum\n");
		return -1;
	}

	unsigned int xauthdatalen = 50;
	char xauthdata[xauthdatalen];
	if(ua_unmarshall_string(d, xauthdata, &xauthdatalen) < 0)
		err(EX_IOERR, "Error unmarshalling Xauth data");

	printf("sandbox:\tXauth data: ");
	for(unsigned int i = 0; i < xauthdatalen; i++) printf("%02x ", xauthdata[i] & 0xff);
	printf("\n");
	fflush(stdout);

	xcb_auth_info_t xauthinfo;
	xauthinfo.namelen = xauthnamelen;
	xauthinfo.name = xauthname;
	xauthinfo.datalen = xauthdatalen;
	xauthinfo.data = xauthdata;

	xcb_auth_cache(&xauthinfo);




	// start QApplication
	printf("sandbox:\tCreating QApplication...\n");
	fflush(stdout);
	QApplication app(argc, argv);
	printf("sandbox:\tQApplication started.\n");



	// display a proper window
	new TextEditor();

	int ret = app.exec();
	printf("sandbox:\tQApplication::exec() returned with code %i\n", ret);
	fflush(stdout);

	return ret;
}



int connect_to_X(int *Xfd, xcb_auth_info_t *auth)
{
	char *host;
	int display;
	int screen;

	bzero(auth, sizeof(*auth));
	if(xcb_parse_display(NULL, &host, &display, &screen) < 0) return -1;

	if(*host)
	{
		*Xfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
		if(*Xfd < 0) return -1;

		int on = 1;
		setsockopt(*Xfd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));

		struct addrinfo hints, *results, *addr;
		bzero(&hints, sizeof(hints));
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;

		char service[6];
		int port = 6000 + display;

		snprintf(service, sizeof(service), "%hu", port);
		if(getaddrinfo(host, service, &hints, &results)) return -1;

		for(addr = results; addr; addr = addr->ai_next)
		{
			*Xfd = socket(addr->ai_family, addr->ai_socktype,
			             addr->ai_protocol);

			if(*Xfd < 0)
			{
				close(*Xfd);
				*Xfd = -1;
				continue;
			}

			

           		int on = 1;
         		setsockopt(*Xfd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));

            		if(!connect(*Xfd, addr->ai_addr, addr->ai_addrlen))
			{
				_xcb_get_auth_info(*Xfd, auth, display);
				break;
			}
		}
		freeaddrinfo(results);

		return 0;
	}
	else
	{
		*Xfd = socket(AF_UNIX, SOCK_STREAM, 0);
		if(*Xfd == -1) return -1;

		char sockname[30];
		if(snprintf(sockname, sizeof(sockname), "/tmp/.X11-unix/X%i",
		            display) < 0)
			return -1;

		struct sockaddr_un addr;
		strcpy(addr.sun_path, sockname);
		addr.sun_family = AF_UNIX;

		if(connect(*Xfd, (struct sockaddr*) &addr, sizeof(addr)))
			return -1;

		_xcb_get_auth_info(*Xfd, auth, display);

		return 0;
	}
}

